<template>
    <a-layout-header class="design-header">
        <div class="left flex items-center">
            <a-button class="mr-2" @click="goProj">
                <Iconfy icon="material-symbols:home"/>
            </a-button>
            <a-tooltip placement="top">
                <template #title>
                    <span>图表列表</span>
                </template>
                <a-button :style="chartListStyle" class="mr-2" @click="changeChartListFlag">
                    <Iconfy icon="solar:book-2-bold"/>
                </a-button>
            </a-tooltip>
            <a-tooltip placement="top">
                <template #title>
                    <span>图层</span>
                </template>
                <a-button :style="layerStyle" class="mr-2" @click="changeLayerFlag">
                    <Iconfy icon="mingcute:layer-fill"/>
                </a-button>
            </a-tooltip>
            <a-tooltip placement="top">
                <template #title>
                    <span>图表配置</span>
                </template>
                <a-button :style="settingStyle" class="mr-5" @click="changeSettingFlag">
                    <Iconfy icon="eos-icons:config-map"/>
                </a-button>
            </a-tooltip>
            <a-tooltip placement="top">
                <template #title>
                    <span>回退</span>
                </template>
                <a-button  :disabled="!isBackStack" @click="handleBack">
                    <Iconfy icon="ooui:next-rtl"/>
                </a-button>
            </a-tooltip>
            <a-tooltip placement="top">
                <template #title>
                    <span>前进</span>
                </template>
                <a-button class="mr-5" :disabled="!isForwardStack" @click="handleForward">
                    <Iconfy icon="ooui:next-ltr"/>
                </a-button>
            </a-tooltip>
            <a-tooltip placement="top">
                <template #title>
                    <span>保存</span>
                </template>
                <a-button @click="handleSave">
                    <Iconfy icon="material-symbols-light:save-rounded"/>
                </a-button>
            </a-tooltip>

        </div>
        
        <div class="center flex items-center"   @click="state.isShow = true">
            <span  v-if="!state.isShow">{{ dataviewState.projDetail.projectName }}</span>
            <a-input v-else v-model:value="dataviewState.projDetail.projectName" placeholder="" @blur="state.isShow =false"/>
        </div>

        <div class="right flex">
            <a-button class="flex items-center mr-2">
                预览
                <Iconfy icon="material-symbols-light:view-in-ar-outline-rounded" class="ml-1"/>
            </a-button>
            <a-button :style="publishStyle" class="flex items-center" @click="handlePublish">
                {{ dataviewState.projDetail.isPublish == 1 ? '已发布' : '未发布'  }}
                <Iconfy icon="entypo:publish" class="ml-1"/>
            </a-button>
            <publish-dialog
                ref="publishDialogRef"
                @update-data-view-project="updateDataViewProject"
            />
        </div>
    </a-layout-header>
</template>

<script setup lang="ts">
import Iconfy from '@/components/Iconify/index.vue'
import {useDataViewStore} from '@/stores/dataview'
import { storeToRefs } from 'pinia'
import { computed, reactive ,ref} from 'vue'
import { useRouter ,useRoute} from 'vue-router'
import { useThemeConfig } from '@/stores/themeConfig'
import { useDataViewLayoutStore } from '@/stores/dataviewLayout'
import {apiDataViewProjectAddPost, apiDataViewProjecUpdatePost, setProjectDataAPi,uploadProjCoverAPI} from '@/api/dataview/project'
import html2canvas from 'html2canvas'
import type { ResType } from '@/api/types'
import type { SysFileType } from '@/views/system/userCenter/types'
import { message } from 'ant-design-vue';
import { showMsg } from '@/utils'
import publishDialog from './components/publishDialog.vue'
import { useDataViewHistoryStore } from '@/stores/dataviewHistory'

const emits = defineEmits<{
    (e:"setLoading",val:boolean):void
}>()

const router = useRouter()
const route = useRoute()

const dataviewStore = useDataViewStore()
const {dataviewState} = storeToRefs(dataviewStore)
const themeConfigStore = useThemeConfig()
const dataviewLayoutStore = useDataViewLayoutStore()
const {dataviewLayoutState} = storeToRefs(dataviewLayoutStore)
const dataviewHistoryStore = useDataViewHistoryStore()
const {dataviewHistoryState} = storeToRefs(dataviewHistoryStore)
const publishDialogRef = ref<InstanceType<typeof publishDialog>>()
const state = reactive({
    isShow:false,
})

const goProj = ()=>{
    router.push({
        path:'/dataview/projects'
    })
}

const chartListStyle = computed(()=>{
    if(dataviewLayoutState.value.isShowChartList){
        return {
            border:`1px solid ${themeConfigStore.themeConfig.primary}`,
            color:themeConfigStore.themeConfig.primary
        }
    }else{
        return {}
    }
})
const layerStyle = computed(()=>{
    if(dataviewLayoutState.value.isShowLayer){
        return {
            border:`1px solid ${themeConfigStore.themeConfig.primary}`,
            color:themeConfigStore.themeConfig.primary
        }
    }else{
        return {}
    }
})
const settingStyle = computed(()=>{
    if(dataviewLayoutState.value.isShowSetting){
        return {
            border:`1px solid ${themeConfigStore.themeConfig.primary}`,
            color:themeConfigStore.themeConfig.primary
        }
    }else{
        return {}
    }
})

const publishStyle = computed(()=>{
    if(dataviewState.value.projDetail.isPublish == 1){
        return {
            border:`1px solid ${themeConfigStore.themeConfig.primary}`,
            color:themeConfigStore.themeConfig.primary
        }
    }else{
        return {}
    }
})

const isBackStack = computed(()=>{
    return dataviewHistoryStore.getBackLen > 1
})

const isForwardStack = computed(()=>{
    return dataviewHistoryStore.getForwardLen > 0
})

const changeChartListFlag = ()=>{
    dataviewLayoutState.value.isShowChartList = !dataviewLayoutState.value.isShowChartList
}
const changeLayerFlag = ()=>{
    dataviewLayoutState.value.isShowLayer = !dataviewLayoutState.value.isShowLayer
}
const changeSettingFlag = ()=>{
    dataviewLayoutState.value.isShowSetting = !dataviewLayoutState.value.isShowSetting
}

const handleHtml2Canvas = ()=>{
    return new Promise((resolve,reject)=>{
        const canvasDom = document.getElementById('canvas') as HTMLDivElement
        const opt = {}
        html2canvas(canvasDom,opt)
        .then((canvas:HTMLCanvasElement)=>{
            let dataURL = canvas.toDataURL('image/png') //base64对象
            function base64ToBlob(base64:string,mimeType:string='image/png') {
                const data = base64.replace(/^data:image\/\w+;base64,/, '');
                const byteArr = atob(data);
                const buffer = []
                let len = byteArr.length;
                while(len--){
                    buffer[len] = byteArr.charCodeAt(len);
                }
                return new Blob([new Uint8Array(buffer)],{type:mimeType})
            }
            
            function blobToFile(blob:Blob,fileName:string,mimeType:string='image/png'){
                return new File([blob],fileName,{type:mimeType})
            }
            const file = blobToFile(base64ToBlob(dataURL),dataviewState.value.projDetail.projectName)
            resolve(file)
        })
    })
}

const updateDataViewProject = async (value:any)=>{
    await apiDataViewProjecUpdatePost({
        id:route.params.id, //更新项目id
        ...dataviewState.value.projDetail,
        ...value
    })

    await dataviewStore.init() //获取新数据
}

// 处理保存
const handleSave = async ()=>{
    emits('setLoading',true)
    const hide = message.loading('正在更新视图中...', 0);
    const {editCanvasConfig,requestGlobalConfig,componentList} = dataviewState.value
    const projId = route.params.id
    const content = JSON.stringify({editCanvasConfig,requestGlobalConfig,componentList,})

    // 更新项目数据
    await setProjectDataAPi({
        content,
        projId
    })
    
    const file:File = await handleHtml2Canvas() as File //画布dom转换canvas，canvas转换为图片后再转为文件
    const res = await uploadProjCoverAPI(file) as ResType<SysFileType>
    const cover = res.data.result.url
    
    // 更新封面
    await updateDataViewProject({
        coverImg:cover,
    })
    
    emits('setLoading',false)
    hide() //清除消息
    showMsg('更新成功','success')
}

const handlePublish = ()=>{
    publishDialogRef.value?.handleOpen()
}

const handleBack = ()=>{
    dataviewStore.setBack()
}

const handleForward = ()=>{
    dataviewStore.setForward()
}
</script>

<style lang="scss" scoped>
.design-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    height: 45px;
    padding:  0 15px;
    border-bottom: 1px solid #f0f0f0;
}
</style>